package test

import scala.annotation.tailrec

object Tailrec{

  def factorial(n: Int): Int = {
    @tailrec
    def go(n: Int, acc: Int): Int = {
      if (n <= 0) acc
      else go(n - 1, n * acc)
    }
    go(n, 1)
  }



  def findFirst(ss:Array[String], key: String) = {
    @annotation.tailrec
    def loop(n: Int): Int = {
      List
      if(n >= ss.length) -1
      else if(ss(n) == key) n
      else loop(n + 1)
    }
    loop(0)
  }

  def findFirst2[A](as:Array[A], p: A => Boolean): Int = {
    @annotation.tailrec
    def loop(n: Int): Int = {
      if(n >= as.length) -1
      else if(p(as(n))) n
      else loop(n + 1)
    }
    loop(0)
  }

  def fib(n: Int): Int = {
    def go(n: Int, acc1: Int,acc2: Int): Int = {
      if(n <= 1) acc1
      else go(n-1, acc2, acc1 + acc2)
    }
    go(n, 0, 1)
  }

  def main(args: Array[String]): Unit = {
    println(findFirst2(Array("a", "b"), (num: String) => num == "a"))
  }
}
